/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.ubc.cc.ajax;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apps.datastore.AccountInformationDatastore;
import com.apps.datastore.dao.AccountObject;
import com.apps.utils.BCryptUtils;
import com.apps.utils.EmailUtils;

public class LoginFormController extends HttpServlet{
	AccountInformationDatastore d = new AccountInformationDatastore();
	private String email;
	private String password;

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		email = req.getParameter("username").toLowerCase();
		password = req.getParameter("password");
		boolean valid = EmailUtils.isValidEmail(email);
		String xmlout = "<authentication>\n";
		if(!valid){
			xmlout += "\t<login>false</login>\n";
			xmlout += "\t<error>Invalid email or password</error>\n";
		}
		else {
			AccountObject obj = login(email, password);

			if (obj != null && obj.isActivated()) {
				xmlout += "\t<login>true</login>\n";
				xmlout += "\t<user>" + obj.getEmail() + "</user>\n";
				xmlout += "\t<key>" + obj.getAuthkey() + "</key>\n";
			} else if (obj == null) {
				xmlout += "\t<login>false</login>\n";
				xmlout += "\t<error>Invalid email or password</error>\n";
			} else if (!obj.isActivated()) {
				xmlout += "\t<login>false</login>\n";
				xmlout += "\t<error>Your account is not activated</error>\n";
			}
		}
		xmlout += "</authentication>";
		try {
			resp.setContentType("text/xml");
			resp.getWriter().write(xmlout);
		} catch (IOException e) {
			e.printStackTrace();
		}


	}

	public AccountObject login(String username, String password) {

		AccountObject lio = d.getAccountObject(username);
		
		if (lio != null ) {
		
			if (BCryptUtils.checkpw(password, lio.getPassword())) {
			} else {
				lio=null;
			}

		}
		return lio;
	}

}
